package com.qianfeng.chainmobile.api.listeners;


import com.qianfeng.chainmobile.api.feign.CacheService;
import com.qianfeng.smsplatform.common.constants.CacheConstants;
import com.qianfeng.smsplatform.common.model.Standard_Report;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

/**
 * Created by Jackiechan on 2021/11/17/18:04
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */
@Component
public class PushReportListener {

    private CacheService cacheService;

    @Autowired
    public void setCacheService(CacheService cacheService) {
        this.cacheService = cacheService;
    }

    private RestTemplate restTemplate;

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }


    @Async
    @EventListener
    public void onEvent(Standard_Report report) {
        //发送请求
        //需要获取用户的地址信息
        String receivestatusurl = cacheService.hGet(CacheConstants.CACHE_PREFIX_CLIENT + report.getClientID(), "receivestatusurl");
        if (!ObjectUtils.isEmpty(receivestatusurl)) {
            //将我们的数据转换成json.然后发送出去
            String result = null;
            try {
                result = restTemplate.postForObject(receivestatusurl, report, String.class);//我们要求用户必须返回一个success字符串
            } catch (Exception e) {
                e.printStackTrace();
            }
            //如果返回的不是success 就不行
            if (!"success".equalsIgnoreCase(result) ) {//没有结果或者是失败的或者是发送的还不够十次 就重新发送
                //发送失败,进入重试的机制中,比如定时任务
                if (report.getSendCount() <= 10) {
                    report.setSendCount(report.getSendCount() + 1);
                }

                //保存结果等待重试
            }else {
                System.err.println("客户已经收到我们的状态报告了");
            }
        }

    }
}
